"""
API路由
"""
import datetime
from typing import List, Dict, Any
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware

from ..services.search_service import SearchService
from .models import *


# 创建FastAPI应用
app = FastAPI(
    title="Data Embedding API",
    description="文档向量化和相似度搜索API",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 创建搜索服务实例
search_service = SearchService()


@app.get("/", response_model=HealthCheckResponse)
async def health_check():
    """健康检查"""
    return HealthCheckResponse(
        status="ok",
        version="1.0.0",
        timestamp=datetime.datetime.now().isoformat()
    )


@app.post("/search", response_model=SearchResponse)
async def search_documents(request: SearchRequest):
    """搜索相似文档"""
    try:
        results = search_service.search(
            query=request.query,
            kb_name=request.kb_name,
            top_k=request.top_k,
            score_threshold=request.score_threshold
        )
        
        return SearchResponse(
            success=True,
            results=results,
            total=len(results),
            query=request.query,
            kb_name=request.kb_name
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/documents/add", response_model=AddDocumentResponse)
async def add_document(request: AddDocumentRequest):
    """添加文档到知识库"""
    try:
        result = search_service.add_document(
            file_path=request.file_path,
            kb_name=request.kb_name,
            chunk_size=request.chunk_size,
            chunk_overlap=request.chunk_overlap,
            splitter_name=request.splitter_name
        )
        
        if result["success"]:
            return AddDocumentResponse(
                success=True,
                doc_count=result["doc_count"],
                doc_ids=result["doc_ids"],
                file_info=result["file_info"]
            )
        else:
            return AddDocumentResponse(
                success=False,
                error=result["error"]
            )
    except Exception as e:
        return AddDocumentResponse(
            success=False,
            error=str(e)
        )


@app.post("/documents/add_batch")
async def add_documents_batch(
    file_paths: List[str],
    kb_name: str = "default",
    chunk_size: int = 750,
    chunk_overlap: int = 150,
    splitter_name: str = "ChineseRecursiveTextSplitter"
):
    """批量添加文档"""
    try:
        results = search_service.add_documents(
            file_paths=file_paths,
            kb_name=kb_name,
            chunk_size=chunk_size,
            chunk_overlap=chunk_overlap,
            splitter_name=splitter_name
        )
        
        return {
            "success": True,
            "results": results,
            "total_files": len(file_paths),
            "successful_files": len([r for r in results if r["success"]])
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.delete("/documents/{file_path}")
async def delete_document(file_path: str, kb_name: str = "default"):
    """删除文档"""
    try:
        success = search_service.delete_document(file_path, kb_name)
        return {"success": success}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/knowledge_bases", response_model=ListKnowledgeBasesResponse)
async def list_knowledge_bases():
    """列出所有知识库"""
    try:
        kb_list = search_service.list_knowledge_bases()
        return ListKnowledgeBasesResponse(
            success=True,
            knowledge_bases=kb_list
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/knowledge_bases/{kb_name}/info", response_model=KnowledgeBaseInfo)
async def get_knowledge_base_info(kb_name: str):
    """获取知识库信息"""
    try:
        info = search_service.get_knowledge_base_info(kb_name)
        return KnowledgeBaseInfo(**info)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/knowledge_bases/{kb_name}/documents")
async def list_documents(kb_name: str):
    """列出知识库中的所有文档"""
    try:
        documents = search_service.list_documents(kb_name)
        return {
            "success": True,
            "documents": documents,
            "total": len(documents)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/knowledge_bases/clear", response_model=ClearKnowledgeBaseResponse)
async def clear_knowledge_base(request: ClearKnowledgeBaseRequest):
    """清空知识库"""
    try:
        success = search_service.clear_knowledge_base(request.kb_name)
        return ClearKnowledgeBaseResponse(
            success=success,
            message="知识库清空成功" if success else "知识库清空失败"
        )
    except Exception as e:
        return ClearKnowledgeBaseResponse(
            success=False,
            message=str(e)
        )


@app.get("/config")
async def get_config():
    """获取配置信息"""
    from ..config.settings import settings
    
    return {
        "embedding": settings.get_embedding_config(),
        "vector_store": settings.get_vector_store_config(),
        "text_splitter": settings.get_text_splitter_config(),
        "search": {
            "top_k": settings.search.top_k,
            "score_threshold": settings.search.score_threshold,
            "search_type": settings.search.search_type,
        }
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000) 